package com.nlp.weixin.web.wx;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSONObject;
import com.nlp.weixin.web.util.HttpRequestProxy;

/**
 * 微信信息缓存，更新
 * @author zyl
 *
 */
public class WeiXin {
	
	private static final Log logger = LogFactory.getLog( WeiXin.class );
	
	private static String appId = null;
	
	private static String appSecret = null;
	
	private static String access_token = null;

	private static String host = null;
	
	private static String jsapi_ticket = null;
	
	public static String getAppId() {
		return appId;
	}

	public static void setAppId(String appId) {
		WeiXin.appId = appId;
	}

	public static String getAppSecret() {
		return appSecret;
	}

	public static void setAppSecret(String appSecret) {
		WeiXin.appSecret = appSecret;
	}

	public static String getAccess_token() {
		return access_token;
	}

	public static void setAccess_token(String access_token) {
		WeiXin.access_token = access_token;
	}

	public static String getHost() {
		return host;
	}

	public static void setHost(String host) {
		WeiXin.host = host;
	}
	
	public static String getJsapi_ticket() {
		return jsapi_ticket;
	}

	public static void setJsapi_ticket(String jsapi_ticket) {
		WeiXin.jsapi_ticket = jsapi_ticket;
	}

	/**
	 * 需要定时刷新
	 * 2小时
	 * @return access_token
	 */
	public static String getAccess_tokenForm(){
		String reqUrl = "https://api.weixin.qq.com/cgi-bin/token?" +
				"grant_type=client_credential" +
				"&appid=" + appId +
				"&secret=" + appSecret;
		String result = HttpRequestProxy.doGet(reqUrl, "UTF-8");
		JSONObject json = JSONObject.parseObject( result );
		if( json.containsKey("access_token") ){
			access_token =  json.getString("access_token");
		}else{
			logger.warn("Can't get access_token from weixin service....");
		}
		return access_token;
	}
	
	/**
	 * 需要定时刷新
	 * 2小时
	 * @return jsapi_ticket
	 */
	public static String getJsApi_TicketForm(){
		if( access_token == null ){
			return null;
		}
		String reqUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?" +
				"access_token=" + access_token +
				"&type=jsapi";
		String result = HttpRequestProxy.doGet(reqUrl, "UTF-8");
		JSONObject json = JSONObject.parseObject( result );
		if( json.containsKey("ticket") ){
			jsapi_ticket =  json.getString("ticket");
		}else{
			logger.warn("Can't get jsapi_ticket from weixin service....");
		}
		return jsapi_ticket;
	}
	
}
